package com.rmy.queue.controller;

import java.io.IOException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.rmy.common.core.text.Convert;
import com.rmy.common.utils.DateUtils;
import com.rmy.common.utils.StringUtils;
import com.rmy.framework.websocket.WebSocketUsers;
import com.rmy.queue.common.ErrorTipsConst;
import com.rmy.queue.common.QueueConst;
import com.rmy.queue.common.TestFunction;
import com.rmy.queue.common.webSocket.CompShowWebSocketServer;
import com.rmy.queue.common.webSocket.ProjectWebSocketServer;
import com.rmy.queue.domain.*;
import com.rmy.queue.service.*;
import com.rmy.system.service.ISysRoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.rmy.common.annotation.Log;
import com.rmy.common.core.controller.BaseController;
import com.rmy.common.core.domain.AjaxResult;
import com.rmy.common.enums.BusinessType;
import com.rmy.common.utils.poi.ExcelUtil;
import com.rmy.common.core.page.TableDataInfo;

/**
 * 预约管理Controller
 *
 * @author rmy
 * @date 2022-09-29
 */
@RestController
@RequestMapping("/queue/mainbusiness")
public class QmsMainBusinessController extends BaseController
{
    @Autowired
    private IQmsMainBusinessService qmsMainBusinessService;

    @Autowired
    private IQmsWindowInfoService qmsWindowInfoService;

    @Autowired
    private IQmsErpRuleService qmsErpRuleService;

    @Autowired
    private IQmsWindowBusinessService qmsWindowBusinessService;

    @Autowired
    private IQmsQueueListService qmsQueueListService;


    /**
     * 查询预约管理列表
     */
    @PreAuthorize("@ss.hasPermi('queue:mainbusiness:list')")
    @GetMapping("/list")
    public TableDataInfo list(QmsMainBusiness qmsMainBusiness)
    {
        startPage();
        List<QmsMainBusiness> list = qmsMainBusinessService.selectQmsMainBusinessList(qmsMainBusiness);
        return getDataTable(list);
    }

    /**
     * 导出预约管理列表
     */
    @PreAuthorize("@ss.hasPermi('queue:mainbusiness:export')")
    @Log(title = "预约管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QmsMainBusiness qmsMainBusiness)
    {
        List<QmsMainBusiness> list = qmsMainBusinessService.selectQmsMainBusinessList(qmsMainBusiness);
        ExcelUtil<QmsMainBusiness> util = new ExcelUtil<QmsMainBusiness>(QmsMainBusiness.class);
        util.exportExcel(response, list, "预约管理数据");
    }

    /**
     * 获取预约管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('queue:mainbusiness:query')")
    @GetMapping(value = "/{mbSerialNo}")
    public AjaxResult getInfo(@PathVariable("mbSerialNo") String mbSerialNo)
    {
        return AjaxResult.success(qmsMainBusinessService.selectQmsMainBusinessByMbSerialNo(mbSerialNo));
    }

    /**
     * 新增预约管理
     */
    @PreAuthorize("@ss.hasPermi('queue:mainbusiness:add') and @ss.lacksRole('admin')")
    @Log(title = "预约管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody QmsMainBusiness qmsMainBusiness)
    {
        // 默认插入操作人员数据
        qmsMainBusiness.setCreateBy(getUsername());
        qmsMainBusiness.setOrgNo(Convert.toStr(getDeptId()));
        qmsMainBusiness.setSourceType("1"); //手动添加
        return toAjax(qmsMainBusinessService.insertQmsMainBusiness(qmsMainBusiness));
    }

    /**
     * 修改预约管理
     */
    @PreAuthorize("@ss.hasPermi('queue:mainbusiness:edit') and @ss.lacksRole('admin')")
    @Log(title = "预约管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody QmsMainBusiness qmsMainBusiness)
    {
        // 设置更新者
        qmsMainBusiness.setUpdateBy(getUsername());
        // 手动添加才能更改信息
        if (!"1".equals(qmsMainBusiness.getSourceType())) {
            return AjaxResult.error("人工添加才能更改信息！");
        }
        return toAjax(qmsMainBusinessService.updateQmsMainBusiness(qmsMainBusiness));
    }

    /**
     * 删除预约管理
     */
    @PreAuthorize("@ss.hasPermi('queue:mainbusiness:remove') and @ss.lacksRole('admin')")
    @Log(title = "预约管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{mbSerialNos}")
    public AjaxResult remove(@PathVariable String[] mbSerialNos)
    {
        return toAjax(qmsMainBusinessService.deleteQmsMainBusinessByMbSerialNos(mbSerialNos));
    }

    /**
     * 模拟自助取号
     */
    @Log(title = "模拟自助取号", businessType = BusinessType.UPDATE)
    @PostMapping("/takenumber/{mbSerialNo}")
    @PreAuthorize("@ss.hasRole('registor')")
    public AjaxResult takenumber(@PathVariable String mbSerialNo)
    {
        QmsMainBusiness qmsMainBusiness = qmsMainBusinessService.selectQmsMainBusinessByMbSerialNo(mbSerialNo);
        if (null == qmsMainBusiness) {
            return AjaxResult.error(ErrorTipsConst.TIPS_BUSINESS_NOT_FOUND);
        }
        if (StringUtils.isNotEmpty(qmsMainBusiness.getSerialNo())) {
            return AjaxResult.error(ErrorTipsConst.TIPS_QUEUE_NO_TAKED);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cmd", QueueConst.WEBSOCKET_CMD.CMD_TAKE_NUMBER_NOTICE);
        ProjectWebSocketServer.sendAllMessage(jsonObject.toString());
        try {
            CompShowWebSocketServer.sendMessage(qmsMainBusiness.getOrgNo(), jsonObject.toString());
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("发送消息给" + qmsMainBusiness.getOrgNo() + "失败");
        }

        // TODO  正式不能这么写 应该先取号再发消息
        return toAjax(qmsMainBusinessService.takeNumber(qmsMainBusiness));
    }

    /**
     * 批量取测试号 每次取10个
     */
    @Log(title = "批量取测试号", businessType = BusinessType.UPDATE)
    @PostMapping("/batchTakeNumber")
    @PreAuthorize("@ss.lacksRole('admin')")
    public AjaxResult batchTakeNumber()
    {
        // 1.随机生成业务数据
        for (int x = 0; x < 15; x++) {
            QmsMainBusiness qmsMainBusiness = new QmsMainBusiness();
            qmsMainBusiness.setCarNo(TestFunction.randomPlateNO());
            qmsMainBusiness.setDriverName(TestFunction.randomName());
            qmsMainBusiness.setDriverIdNo(TestFunction.randomIDNo());
            qmsMainBusiness.setDriverPhone(TestFunction.randomPhone());
            qmsMainBusiness.setOrgNo(Convert.toStr(getDeptId()));
            Random random = new Random();
            int op = random.nextInt(2) + 1;
            qmsMainBusiness.setErpBillType(Convert.toStr(op));
            qmsMainBusiness.setErpBillNo("1234567890");
            qmsMainBusiness.setTargetDate(DateUtils.getNowDate());
            op = random.nextInt(2) + 1;
            qmsMainBusiness.setBusinessType(Convert.toStr(op));
            op = random.nextInt(2) + 1;
            qmsMainBusiness.setSourceType(Convert.toStr(op));
            qmsMainBusiness.setCreateBy(getUsername());
            qmsMainBusiness.setBookingStartTime("08:00");
            qmsMainBusiness.setBookingEndTime("10:00");
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            qmsMainBusinessService.insertQmsMainBusiness(qmsMainBusiness);
            qmsMainBusinessService.takeNumber(qmsMainBusiness);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cmd", QueueConst.WEBSOCKET_CMD.CMD_TAKE_NUMBER_NOTICE);
        ProjectWebSocketServer.sendAllMessage(jsonObject.toString());
        try {
            CompShowWebSocketServer.sendMessage(Convert.toStr(getDeptId()), jsonObject.toString());
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("发送消息给" + Convert.toStr(getDeptId()) + "失败");
        }
        return AjaxResult.success("批量(15)取号完成");
    }


    /**
     * 根据uuid查询叫号队列列表
     */
    @GetMapping("/selectQueueListByUUID")
    public TableDataInfo selectQueueListByUUID(QmsMainBusiness qmsMainBusiness) throws Exception {
        List<QmsMainBusiness> list = new ArrayList<>();
        list = qmsMainBusinessService.selectQueueListByUUID(qmsMainBusiness);
        return getDataTable(list);
    }


    /**
     * 业务叫号
     */
    @Log(title = "业务叫号", businessType = BusinessType.UPDATE)
    @PostMapping("/callbusinessnumber")
    public AjaxResult callbusinessnumber(@RequestParam String windowUuid) throws Exception {
        QmsMainBusiness qmsMainBusiness = qmsMainBusinessService.callBusinessNumber(windowUuid);
        return AjaxResult.success(qmsMainBusiness);
    }


    /**
     * 重呼
     */
    @Log(title = "重复呼叫", businessType = BusinessType.UPDATE)
    @PostMapping("/recall")
    public AjaxResult recall(@RequestParam String windowUuid) throws Exception {
        return AjaxResult.success(qmsMainBusinessService.recallBusinessNumber(windowUuid));
    }


    /**
     * 跳过
     */
    @Log(title = "叫号跳过", businessType = BusinessType.UPDATE)
    @PostMapping("/ignore")
    public AjaxResult ignore(@RequestParam String windowUuid) throws Exception {

        return AjaxResult.success(qmsMainBusinessService.ignoreBusinessNumber(windowUuid));
    }

    /**
     * 指定呼叫
     */
    @Log(title = "指定呼叫", businessType = BusinessType.UPDATE)
    @PostMapping("/callbyqueueno")
    public AjaxResult callbyqueueno(@RequestParam String windowUuid, @RequestParam String queueNo) throws Exception {

        return AjaxResult.success( qmsMainBusinessService.callByQueueNumber(windowUuid, queueNo));
    }


    /**
     * 叫号完成
     */
    @Log(title = "预约登记", businessType = BusinessType.UPDATE)
    @PostMapping("/callover/{serialNo}")
    public AjaxResult callover(@PathVariable String serialNo)
    {
        QmsMainBusiness tmpSelect = new QmsMainBusiness();
        tmpSelect.setSerialNo(serialNo);
        List<QmsMainBusiness> qmsMainBusinessList = qmsMainBusinessService.selectQmsMainBusinessList(tmpSelect);
        if (null == qmsMainBusinessList || qmsMainBusinessList.size() == 0) {
            return AjaxResult.error(ErrorTipsConst.TIPS_BUSINESS_NOT_FOUND);
        }
        QmsMainBusiness qmsMainBusiness = qmsMainBusinessList.get(0);
        // 已叫号
        qmsMainBusiness.setFlowStatus(QueueConst.FLOW_STATUS.已叫号);
        qmsMainBusinessService.updateQmsMainBusiness(qmsMainBusiness);

        return AjaxResult.success(qmsMainBusiness);
    }



    /**
     * 查询当前正在叫号
     */
    @GetMapping("/selectCurCallQueueNo")
    public AjaxResult selectCurCallQueueNo(@RequestParam String windowUuid)
    {
        return AjaxResult.success(qmsMainBusinessService.selectCurCallQueueNo(windowUuid));
    }

    /**
     * 根据机构查询鹤位列表
     */
    @GetMapping("/selectWindowListByDept")
    public TableDataInfo selectWindowListByDept()
    {
        // 获取当前机构
        String orgNo = Convert.toStr(getDeptId());
        startPage();
        List<QmsWindowInfo> list = qmsMainBusinessService.selectWindowListByDept(orgNo);
        return getDataTable(list);
    }

    /**
     * 根据机构、窗口查询已取号列表
     */
    @GetMapping("/selectBusinessQueueListTaked")
    public TableDataInfo selectBusinessQueueListTaked(QmsMainBusiness qmsMainBusiness)
    {
        String orgNo = Convert.toStr(getDeptId());
        qmsMainBusiness.setOrgNo(orgNo);
        startPage();
        List<QmsMainBusiness> list = qmsMainBusinessService.selectBusinessQueueListTaked(qmsMainBusiness);
        return getDataTable(list);
    }


    /**
     * 根据机构、窗口查询已呼叫列表
     */
    @GetMapping("/selectBusinessQueueListCalled")
    public TableDataInfo selectBusinessQueueListCalled(QmsMainBusiness qmsMainBusiness)
    {
        String orgNo = Convert.toStr(getDeptId());
        qmsMainBusiness.setOrgNo(orgNo);
        startPage();
        List<QmsMainBusiness> list = qmsMainBusinessService.selectBusinessQueueListCalled(qmsMainBusiness);
        return getDataTable(list);
    }


    /**
     * 模拟进场
     */
    @Log(title = "模拟进场", businessType = BusinessType.UPDATE)
    @PostMapping("/entryTest/{mbSerialNo}")
    public AjaxResult entryTest(@PathVariable String mbSerialNo)
    {
        QmsMainBusiness qmsMainBusiness = new QmsMainBusiness();
        qmsMainBusiness.setFlowStatus(QueueConst.FLOW_STATUS.已进场);
        qmsMainBusiness.setMbSerialNo(mbSerialNo);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cmd", QueueConst.WEBSOCKET_CMD.CMD_STATUS_CHANGE_NOTICE);
        ProjectWebSocketServer.sendAllMessage(jsonObject.toString());
        return toAjax(qmsMainBusinessService.updateQmsMainBusiness(qmsMainBusiness));
    }



}
